package org.chouy.utils.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.assertj.core.util.Maps;
import springfox.documentation.spring.web.json.Json;

import javax.xml.ws.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: Yang
 * @description: Http接口测试
 * @author: Zhouy
 * @create: 2019-01-07 10:24
 **/
public class HttpApiTest {

    public static JSONObject interfaceInvoke(String link,String data){
        URL url;
        JSONObject jsonObject = new JSONObject();
        Map<Object,Object> map = null;
        {
            try {

                url = new URL(link);
                map = new HashMap<>(10);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("accept","*/*");
                connection.setRequestProperty("connection","Keep-Alive");
                connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                PrintWriter out = new PrintWriter(connection.getOutputStream());
                out.print(data);
                out.flush();
                InputStream is = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is,"GBK"));
                String str = "";
                StringBuilder outData = new StringBuilder();
                while ((str = br.readLine())!=null) {
                    outData.append(str);
                    System.out.println(str);
                }
                map.put("data",outData.toString());
                jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
                is.close();
                connection.disconnect();
                System.out.println("完成");

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    }

    public static void main(String[] args) {
        JSONObject jsonObject = interfaceInvoke("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm","tel=15000214549");
        String data = jsonObject.getString("data");
        data = data.substring(data.indexOf("{"),data.length()).trim();
        jsonObject = JSONObject.parseObject(data);
        System.out.println(jsonObject.getString("catName"));
        //interfacePhoneNumber("http://gc.ditu.aliyun.com/geocoding","a=荆州市");
    }


}
